var app = getApp();
var ajax = require('./ajax.js');
// var Config = require('../config.js');

var isExtInited = false;
var sysInfo = undefined;

//初始化app
function initApp(options) {
  var {
    extSuc,
    loginSuc,
    sysInfoSuc,
    fetchSysInfo = false, //是否强制获取系统信息
  } = options || {};

  initExtConfig(function () {
    extSuc && extSuc();

    quietLogin(function () {
      loginSuc && loginSuc();
      getSysInfo((sysInfo) => {
        sysInfoSuc && sysInfoSuc(sysInfo);
      }, fetchSysInfo);
    });
  });
}

//读取系统信息
function getSysInfo(cb, fetchSysInfo) {

  if (!fetchSysInfo && sysInfo) {
    return cb && cb(sysInfo);
  }

  wx.getSystemInfo({
    complete: (res) => {
      const {
        windowHeight,
        windowWidth
            } = res;

      sysInfo = res;
      windowHeight && app.setWinHei(windowHeight);
      windowWidth && app.setWinWid(windowWidth);

      cb && cb(res);
    },
  });
}

//初始化配置信息
function initExtConfig(cb) {
  if (isExtInited) {
    return cb && cb();
  }
  wx.getExtConfig && wx.getExtConfig({
    success: function (res) {
      var {
        host,
        alias,
        tabBar
            } = res.extConfig;

      isExtInited = true;
      if (host) {
        app.setHost(host);
      }
      if (alias) {
        app.setAlias(alias);
      }
      if (tabBar) {
        app.config.tabBar = tabBar;
      }
      cb && cb();
    }
  });
}

/**
 * 静默登陆
 */
function quietLogin(cb) {
  //检验登录态是否过期
  wx.checkSession({
    success: function () { //session没有过期
      if (app.getUid()) {
        cb && cb();
        return;
      }
      else{
        doLogin(cb);
      }
    },
    fail: function () { //session已过期
      doLogin(cb);
    }
  });
}

function doLogin(cb) {
  wx.login({
    success: function (res) {
      var params = {
        wxcode: res.code,
        recuid: app.getRecuid()
      };

      // if (userInfo) {
      //   params.nickName = userInfo.nickName;
      //   params.avatarUrl = userInfo.avatarUrl;
      // };

      ajax.P({
        url: 'm=user&c=register',
        data: params,
        success: (res) => {
          var data = res.data;
          //var appType = data.app_type;
          //var openid = data.openid;
          //var sid = data.sid;
          var uid = data.uid;
          // var mobile = data.mobile;
          // var nickname = data.user_1520220750;
          // var sex = data.sex;
          // var avatar = data.logo;
          var userInfo = {
              mobile: data.mobile,
              nickname: data.nickname,
              sex: data.sex,
              avatar: data.logo
          };
          //var user_id = data.user_id;
          //var techId = data.tech_id;

          // var logoImg = data.logo;
          // var shareTitle = data.share_title;
          // var marketTitle = data.title;

          // app.globalData.sid = sid || '';

          // if (openid) {
          //   app.setOpenId(openid);
          // }

          if (userInfo) {
            app.setUInfo(userInfo);
          };
          if (uid) {
            app.setUid(uid);
          };
          console.log(app.globalData.userInfo);
          //更新个人资料
          updateUserInfo(cb);
          //cb && cb();
        }
      });
    },
    fail: function () { },
    complete: function () {}
  });
}

//更新个人资料
function updateUserInfo(cb){
  app.getUserInfo(function (userInfo) {
      ajax.P({
        url: 'm=user&c=index&a=info',
        data: {
          uid: app.getUid(),
          nickname: userInfo.nickName,
          logo: userInfo.avatarUrl,
          sex: userInfo.gender,
          province: userInfo.province,
          city: userInfo.city,
          country: userInfo.country,
          brand: app.getBrand() || '',
          model: app.getModel() || ''
        },
        success: (res) => {
          app.setUInfo(res.data);
          cb && cb();

        },
        fail: () => {
          cb && cb();

        }
      });

  });
}

function jump(evt) {
  var formId = evt.detail.formId;
  var {
    openType,
    url,
    mustLogin
    } = evt.currentTarget.dataset
  var isLogin = !!app.getUid();
  if (mustLogin && !isLogin) {
    wx.navigateTo({
      url: '/pages/login/index'
    });
    return;
  }

  if (openType == 'navigate' || !openType) {
    openType = 'navigateTo';
  }

  wx[openType]({
    url
  });
  submitForm(formId);
}

//提交表单id
function submitForm(formId) {
  // if (!formId) {
  //   return;
  // }
  // ajax.P({
  //   url: '/common/User/addFormId',
  //   data: {
  //     openId: app.getOpenId(),
  //     formId
  //   },
  //   success: function (res) { }
  // });
}

//提交支付id
function submitPrepay(prepayId) {
  if (!prepayId) {
    return
  }
  ajax.P({
    url: '/common/User/addPrePayId',
    data: {
      openId: app.getOpenId(),
      prepayId,
    },
    success: function (res) { }
  });
}

const pageMedhods = ['onLoad', 'onReady', 'onShow', 'onHide', 'onUnload', 'onPullDownRefresh', 'onReachBottom', 'onShareAppMessage', 'onPageScroll'];

function extend(Child, Parent) {
  var F = function () { };
  F.prototype = Parent.prototype;
  Child.prototype = new F();
  Child.prototype.constructor = Child;
  Child.uber = Parent.prototype;
}

//合并两个Page对象
function extendPage(source, obj) {
  if (!source || !obj) {
    return;
  }
  var newObj = {};
  var newData = {};

  Object.assign(newData, source['data']);
  Object.assign(newData, obj['data']);

  Object.assign(newObj, source);
  Object.assign(newObj, obj);

  newObj['data'] = newData;

  pageMedhods.forEach(function (methodName) {
    var sourceFunc = source[methodName];
    var objFunc = obj[methodName];

    if (sourceFunc && objFunc) {
      newObj[methodName] = function (...params) {
        sourceFunc.bind(this)(...params);
        objFunc.bind(this)(...params);
      }
    }
  });

  return newObj;
}

var pageIndex = 0;
var pageList = ['/pages/mPage1/index', '/pages/mPage2/index', '/pages/mPage3/index'];

//跳转到某个自定义页面
function goToPage(pageId) {
  if (!pageId) {
    return;
  }
  var openType = 'navigateTo';
  var maxIndex = pageList.length - 1;
  var tabBar = app.config.tabBar;
  var toBarName;

  if (pageIndex > maxIndex) {
    openType = 'redirectTo';
  }

  if (tabBar) {
    Object.keys(tabBar).some(function (key) {
      if (tabBar[key] == pageId) {
        openType = 'switchTab';
        toBarName = key;
        return true;
      }
    });
  }

  if (openType == 'switchTab') {
    wx[openType]({
      url: '/pages/' + toBarName + '/index'
    });
    pageIndex = 0;
  } else {
    wx[openType]({
      url: pageList[pageIndex > maxIndex ? maxIndex : pageIndex] + '?pageId=' + pageId
    });
    pageIndex++;
  }
}

function goBackPage() {
  pageIndex--;
}

module.exports = {
  initApp,
  quietLogin,
  submitForm,
  jump,
  extend,
  extendPage,
  goToPage,
  goBackPage,
  submitPrepay
};